package com.vitria.m3oui.rest.app.mgr;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.activation.MimetypesFileTypeMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.apache.log4j.Logger;

/**
 * @author sinaWeibo
 * 
 */
public class HttpClient implements java.io.Serializable {

	private static HttpHost targetHost = new HttpHost("10.111.3.116", 8780);
	//private static HttpGet loginhttpget = new HttpGet("/m3oui/rest/login?username={name}&password={pwd}");
	private static String loginurl = "/m3oui/rest/login?username={name}&password={pwd}";
	
	static Logger log = Logger.getLogger(HttpClient.class.getName());


	public HttpClient() {
		// change timeout to 2s avoid block thread-pool (Tim)
	}

	public static void test(){
	}
	
	public static DefaultHttpClient login(String uname, String pass){
		DefaultHttpClient httpclient = new DefaultHttpClient();
	    ClientConnectionManager mgr = httpclient.getConnectionManager();
	    HttpParams params = httpclient.getParams();
	    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, 
	            mgr.getSchemeRegistry()), params);
	    HttpGet loginhttpget = new HttpGet(loginurl.replace("{name}", uname).replace("{pwd}", pass));
		try {
			httpclient.execute(targetHost, loginhttpget);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return httpclient;
	}
	
	public static String get(DefaultHttpClient httpclient, String url){
		HttpGet httpget = new HttpGet(url);
		try {
			return getResponse(httpclient.execute(targetHost, httpget));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String post(DefaultHttpClient httpclient, String url, List<NameValuePair> params){
		HttpPost httppost = new HttpPost(url);
		try {
			HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8");  
			httppost.setEntity(httpentity);
			return getResponse(httpclient.execute(targetHost, httppost));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void showCookies(DefaultHttpClient httpclient){
		List<Cookie> cookies = httpclient.getCookieStore().getCookies();
		for(Cookie cookie:cookies){
			System.out.println(cookie.getName()+":"+cookie.getValue());			
		}
	}

	public static String getResponse(HttpResponse response){
		if(response == null || response.getEntity() == null)
			return null;
		HttpEntity entity = response.getEntity();
		System.out.println("----------------------------------------");
		System.out.println(response.getStatusLine());
		if (entity != null) {
		System.out.println("Response content length: " + entity.getContentLength());
		}
		// 显示结果
		BufferedReader reader;
		StringBuffer sb = new StringBuffer();
		try {
			reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
				sb.append(line);
			}
			if (entity != null) {
				entity.consumeContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
			HttpClient.login("vtbaadmin","vitria");
	}
}
